/**
 *  @author Cornelius Huang
 *  skill table item
 */
app.directive('skillItem', [function() {
	return {
		restrict: 'AE',
		transclude: false,
		templateUrl: './views/skillItem.html',
		scope: {
			skill: '<?',
			abilities: '=?',
			levels: '<?',
			infoChange: '&?'
		},
		controller: ['$rootScope', '$scope', function($rootScope, $scope) {
			
			$scope.skillObj;
			
			this.$onInit = function() {
				//console.log('on init');
				var levelInfo = getlevelInfo($scope.skill.name);
				$scope.skillObj = getTotalLevelInfo($scope.skill.name);
				$scope.experience = levelInfo.experience;
				$scope.level = getLevelObj(levelInfo.level);
				console.log(levelInfo);
				console.log($scope.level);
			};
			
			var getTotalLevelInfo = function(skill) {
				var totalLevelInfo = null;
				$scope.abilities.forEach(function(ability) {
					if(ability.skill == skill) {
						console.log(ability);
						totalLevelInfo = ability;
					}
				});
				return totalLevelInfo;
			}
			
			var getlevelInfo = function(skill) {
				var levelInfo = new Object();
				levelInfo.experience = null;
				levelInfo.level = null;
				$scope.abilities.forEach(function(ability) {
					if(ability.skill == skill) {
						levelInfo.experience = Number.parseInt(ability.experience);
						levelInfo.level = ability.level;
					}
				});
				return levelInfo;
			}
			
			var getLevelObj = function(levelName) {
				var matchlevelObj = null;	
				$scope.levels.forEach(function(levelObj) {
					if(levelObj.level == levelName) {
						matchlevelObj = levelObj;
					}
				});
				return matchlevelObj;
			}
			
			$scope.skillChange = function() {
				//console.log('skillChange');
				var skillObj = {
					id: null,
					skill: null,
					username: null,
					fullName: null,
					experience: null,
					level: null
				};
				var experience = $scope.experience;
				var level = $scope.level;
				
				if($scope.skillObj != null) {
					//TODO: update	
					skillObj = $scope.skillObj;
					skillObj.experience = experience.toString();
					skillObj.level = level.level;
					$scope.infoChange({output: skillObj});
				} else {
					//TODO: add
					var userInfo = $rootScope.userInfo;
					skillObj.skill = $scope.skill.name;
					skillObj.username = userInfo.username;
					skillObj.fullName = userInfo.fullName;
					//skillObj.experience = experience.toString();
					//skillObj.level = level.level;
					if(experience != null && level != null) {
						skillObj.experience = experience.toString();
						skillObj.level = level.level;
						$scope.infoChange({output: skillObj});
					}
				}
			}
			
			//console.log($scope.abilities);
		}]
	}
}]);

//app.directive()